package dao.impl;

import bean.Car;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import dao.CarDao;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import utils.PageUtil;

import java.sql.SQLException;
import java.util.List;

public class CarDaoImpl implements CarDao {
    QueryRunner runner = new QueryRunner(new ComboPooledDataSource());

    @Override
    public int getTotalCount() {
        String sql ="select count(*) from car";
        int count = 0;
        try {
            Object obj = runner.query(sql, new ScalarHandler<>());
            count = Integer.parseInt(obj.toString());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return count;
    }

    @Override
    public List<Car> findByPage(PageUtil pu) {
        String sql = "select * from car limit ?,?";
        List<Car> list = null;
        try {
            list = runner.query(sql, new BeanListHandler<>(Car.class),pu.getStartIndex(),pu.getPageSize());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    @Override
    public int addCar(Car car) {
        String sql = "insert into car (brand,color,price) values (?,?,?)";
        int row = 0;
        try {
            row = runner.update(sql, car.getBrand(), car.getColor(), car.getPrice());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return row;
    }
}
